'use client';

import * as React from 'react';
import { CheckIcon } from 'lucide-react';

import { cn } from '@/lib/utils';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar';


// type Props = {
//   list: TaskPerformer[];
//   children: React.ReactNode;
//   setPerformrs([]): void;
// };

export const PopoverMultiselectPerformer = ({ list, children, setPerformrs }: any) => {
  const [open, setOpen] = React.useState(false);
  const [array, setArray] = React.useState<TaskPerformer[]>([]);

  const addOrRemove = (array: TaskPerformer[], element: TaskPerformer) => {
    const index = array.findIndex((item) => item.id === element.id);
    let newArray: TaskPerformer[] = [...array];
    if (index === -1) {
      newArray.push(element);
    } else {
      newArray.splice(index, 1);
    }
    setPerformrs(newArray);
    return newArray;
  };

  const firstCase = (userName: string): string => {
    return userName
      .split(' ')
      .map((item) => item.charAt(0))
      .join('');
  };

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>{children}</PopoverTrigger>
      <PopoverContent className='w-[200px] p-0'>
        <Command>
          <CommandInput placeholder='Search performers...' className='h-9' />
          <CommandList>
            <CommandEmpty>Не найден  исполнитель.</CommandEmpty>
            <CommandGroup>
              {list.map((item: TaskPerformer) => (
                <CommandItem
                  key={item.id + item.name}
                  value={item.id.toString()}
                  onSelect={() => {
                    setArray((prev) => addOrRemove(prev, item));
                  }}
                >
                  <Avatar className='flex size-7 min-h-7 min-w-7 items-center justify-center overflow-hidden rounded-full bg-slate-100 mr-2'>
                    <AvatarImage src={item.image} className='object-cover' />
                    <AvatarFallback>{firstCase(item.name)}</AvatarFallback>
                  </Avatar>
                  {item.name}
                  <CheckIcon
                    className={cn(
                      'ml-auto h-4 w-4',
                      array.some((j) => j.id === item.id) ? 'opacity-100' : 'opacity-0'
                    )}
                  />
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
};
